import mido
from mido import MidiFile, MidiTrack, Message
import pygame
import subprocess
import os

# 定义旋律
notes = ['E5', 'D#5', 'E5', 'D#5', 'E5', 'B4', 'D5', 'C5']
durations = [0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5]  # 以四分音符为单位

# MIDI音符映射（吉他音色通常在第31到第40通道）
note_to_midi = {
    'E2': 40, 'F2': 41, 'F#2': 42, 'G2': 43, 'G#2': 44, 'A2': 45,
    'A#2': 46, 'B2': 47, 'C3': 48, 'C#3': 49, 'D3': 50, 'D#3': 51,
    'E3': 52, 'F3': 53, 'F#3': 54, 'G3': 55, 'G#3': 56, 'A3': 57,
    'A#3': 58, 'B3': 59, 'C4': 60, 'C#4': 61, 'D4': 62, 'D#4': 63,
    'E4': 64, 'F4': 65, 'F#4': 66, 'G4': 67, 'G#4': 68, 'A4': 69,
    'A#4': 70, 'B4': 71, 'C5': 72, 'C#5': 73, 'D5': 74, 'D#5': 75,
    'E5': 76
}

# 创建MIDI文件
mid = MidiFile()
track = MidiTrack()
mid.tracks.append(track)

# 设置吉他音色（通常在31到40之间）
track.append(Message('program_change', program=30, time=0))

# 添加音符
for note, duration in zip(notes, durations):
    midi_note = note_to_midi[note]
    track.append(Message('note_on', note=midi_note, velocity=64, time=0))
    track.append(Message('note_off', note=midi_note, velocity=64, time=int(duration * mido.second2tick(1, mid.ticks_per_beat, 500000))))

# 保存MIDI文件
midi_filename = 'guitar_lick.mid'
mid.save(midi_filename)

# 使用FluidSynth将MIDI转换为WAV
sf2_path = 'path/to/guitar_soundfont.sf2'  # 替换为你的吉他音色库路径
wav_filename = 'guitar_lick.wav'
subprocess.run(['fluidsynth', '-i', sf2_path, midi_filename, '-F', wav_filename])

# 播放WAV文件
pygame.mixer.init()
pygame.mixer.music.load(wav_filename)
pygame.mixer.music.play()

# 等待音乐播放完毕
while pygame.mixer.music.get_busy():
    pygame.time.Clock().tick(10)
